import router from "./router/index.js";
import store from "./store/index.js";
import {validatenull} from "@/util/validate.js";
import {getToken} from "@/util/store.js";
import NProgress from "nprogress";
import "nprogress/nprogress.css";

NProgress.configure({showSpinner: false});

router.beforeEach((to, from, next) => {
    NProgress.start();
    if (store.getters.model === "default") {
        if (to.name === "首页") {
            store.dispatch("UpdateCollapse", false);
        }
    }
    const meta = to.meta || {};
    if (getToken()) {
        if (to.path.indexOf("login") !== -1) {
            next({path: "/"});
        } else {
            if (store.getters.token.length === 0) {
                store.dispatch("FedLogOut").then(() => {
                    next({path: "/login"});
                });
            } else {
                const value = to.query.src || to.fullPath;
                const label = to.query.name || to.name;
                const meta = to.meta || {};
                if (!validatenull(value) && !validatenull(label)) {
                    store.commit("ADD_TAG", {
                        label: label,
                        value: value,
                        params: to.params,
                        query: to.query,
                        meta: meta,
                    });
                }
                next();
            }
        }
    } else {
        if (to.path.indexOf("login") !== -1) {
            next();
        }else {
            next("/login");
        }
    }
});

router.afterEach(() => {
    NProgress.done();
    router.$quickRouter.setTitle(store.getters.tag.label);
});
